<template>
  <div>
    <h2>用户管理</h2>
    <!-- 添加用户 -->
    <form @submit.prevent="handleAddUser" style="margin-bottom:1em">
      <input v-model="newUser.username" placeholder="用户名" />
      <input v-model="newUser.phone" placeholder="手机号" />
      <input v-model="newUser.password" type="password" placeholder="密码" />
      <button type="submit">添加用户</button>
    </form>

    <p v-if="error" style="color:red">{{ error }}</p>

    <!-- 用户列表 -->
    <table border="1" cellpadding="5">
      <thead>
        <tr>
          <th>ID</th><th>用户名</th><th>手机号</th><th>权限</th><th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="user in users" :key="user.userId">
          <td>{{ user.userId }}</td>
          <td><input v-model="user.username" /></td>
          <td><input v-model="user.phone" /></td>
          <td><input v-model="user.permissions" /></td>
          <td>
            <button @click="handleUpdateUser(user)">更新</button>
            <button @click="handleDeleteUser(user.userId)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import service from '@/utils/request'

const users = ref([])
const error = ref('')

const newUser = reactive({ username: '', phone: '', password: '' })

async function fetchUsers() {
  try {
    const res = await service.get('/admin/users')
    if (res.data.code === 0) {
      users.value = res.data.data.users
      error.value = ''
    } else {
      error.value = res.data.message
    }
  } catch {
    error.value = '获取列表失败'
  }
}

async function handleAddUser() {
  try {
    const res = await service.post('/admin/users', { ...newUser })
    if (res.data.code === 0) {
      await fetchUsers()
      newUser.username = newUser.phone = newUser.password = ''
    } else {
      error.value = res.data.message
    }
  } catch {
    error.value = '添加失败'
  }
}

async function handleUpdateUser(u) {
  try {
    const res = await service.post(`/admin/users/${u.userId}`, {
      username: u.username,
      phone: u.phone,
      permissions: u.permissions
    })
    if (res.data.code === 0) await fetchUsers()
    else error.value = res.data.message
  } catch {
    error.value = '更新失败'
  }
}

async function handleDeleteUser(id) {
  try {
    await service.delete(`/admin/users/${id}`)
    await fetchUsers()
  } catch {
    error.value = '删除失败'
  }
}

onMounted(fetchUsers)
</script>
